package uabc.arduino.componentes;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JCheckBox;

import uabc.arduino.monitores.Monitor;

public class ItemSalidaDigital extends JCheckBox implements Observer {
	private Monitor monitor;
	private int pin;
	public ItemSalidaDigital(String nombre, Monitor monitor, int pin) {
		super("D"+pin+" "+nombre);
		this.monitor=monitor;
		this.pin=pin;
		this.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				System.out.println("Cambio");
				if (e.getStateChange() == e.SELECTED){
					ItemSalidaDigital.this.monitor.ejecutarComando(
							"3" + ItemSalidaDigital.this.pin + ":1");
					delay(300);
				}
				else{
					ItemSalidaDigital.this.monitor.ejecutarComando(
							"3" + ItemSalidaDigital.this.pin + ":0");
					delay(300);
				}
			}
		});
	}
	
	@Override
	public void update(Observable o, Object arg) {
		String cadena = (String) arg;
		if (cadena.startsWith("S:")) {
			cadena = cadena.substring(2);
			HashMap<String, Double> valores = decodificar(cadena);
			Double v = valores.get("D"+pin);
			if(v!=null){
				if(this.isSelected()){
					if(v==0)
						this.setSelected(false);
				}
				else
					if(v==1)
						this.setSelected(true);
					
			}
		}
			
	}
	
	public HashMap<String, Double> decodificar(String cadena) {
		String[] entradas = cadena.split("-");
		HashMap<String, Double> mapa = new HashMap<String, Double>();
		for (int i = 0; i < entradas.length; i++) {
			String[] entrada = entradas[i].split(":");
			mapa.put(entrada[0], Double.parseDouble(entrada[1]));
		}
		return mapa;
	}
	
	public void delay(long miliSeconds) {
		try {
			Thread.sleep(miliSeconds);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
